// Dify API 配置
const DIFY_BASE_URL = 'http://10.81.129.79';
const DIFY_API_KEY = 'app-RwK5TcIVMw2hx2c06La9ViQJ';

// 年度需求预测对话接口（直接调用Dify API）
export async function demandForecastChat(params: {
  query: string;
  conversation_id?: string;
  user?: string;
  onMessage?: (message: string) => void;
  onError?: (error: Error) => void;
  onComplete?: () => void;
}) {
  const { query, conversation_id, user, onMessage, onError, onComplete } = params;
  
  try {
    const requestBody = {
      inputs: {},
      query,
      response_mode: 'streaming',
      conversation_id: conversation_id || undefined,
      user: user || 'user',
    };

    console.log('Dify API请求:', {
      url: `${DIFY_BASE_URL}/v1/chat-messages`,
      body: requestBody,
    });

    const response = await fetch(`${DIFY_BASE_URL}/v1/chat-messages`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${DIFY_API_KEY}`,
      },
      body: JSON.stringify(requestBody),
    });

    console.log('Dify API响应状态:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text();
      console.error('Dify API错误响应:', errorText);
      throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
    }

    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('Response body is not readable');
    }

    const decoder = new TextDecoder();
    let buffer = '';
    let fullResponse = '';
    let conversationId = conversation_id;
    let hasReceivedData = false;

    console.log('开始读取流式响应...');

    while (true) {
      const { done, value } = await reader.read();
      
      if (done) {
        console.log('流式响应读取完成');
        // 流结束时触发完成回调
        onComplete?.();
        break;
      }

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (!line.trim()) continue;
        
        console.log('收到SSE行:', line);
        
        // 处理SSE格式: data: {...} 或 event: xxx
        if (line.startsWith('data: ')) {
          const data = line.slice(6).trim();
          if (data === '[DONE]' || data === '') {
            continue;
          }
          
          try {
            const json = JSON.parse(data);
            console.log('解析的JSON数据:', json);
            
            // Dify的响应格式可能有多种
            // 1. event字段格式: {event: 'message', answer: '...', conversation_id: '...'}
            // 2. 直接包含answer字段: {answer: '...', conversation_id: '...'}
            
            if (json.event) {
              // 有event字段的情况
              if (json.event === 'message' || json.event === 'message_chunk' || json.event === 'message_file' || json.event === 'agent_message') {
                // 获取答案内容 - Dify流式响应中answer字段通常是增量内容
                const answerText = json.answer || json.text || json.content || '';
                if (answerText) {
                  // Dify的流式响应：message_chunk通常是增量，message可能包含完整或增量
                  // 检查answer是否是新内容（增量）
                  if (json.event === 'message_chunk' || json.answer) {
                    // Dify流式响应规则：
                    // message_chunk: answer是增量文本，直接累加
                    // message: answer是累积内容，直接替换
                    if (json.event === 'message_chunk') {
                      // chunk事件，answer是增量，累加
                      fullResponse += answerText;
                      hasReceivedData = true;
                      console.log('收到chunk增量，当前总长度:', fullResponse.length, '本次增量:', answerText.substring(0, 30));
                    } else {
                      // message事件，answer是累积内容（从开始到当前的全部文本），直接替换
                      // 确保每次收到更长的内容都更新，实现流式效果
                      if (!fullResponse || answerText.length >= fullResponse.length) {
                        const previousLength = fullResponse.length;
                        fullResponse = answerText;
                        hasReceivedData = true;
                        const newLength = answerText.length - previousLength;
                        console.log('收到message累积更新，总长度:', fullResponse.length, '新增:', newLength);
                      }
                    }
                  } else {
                    // 没有answer字段，尝试其他字段
                    if (json.text || json.content) {
                      const text = json.text || json.content;
                      fullResponse += text;
                      hasReceivedData = true;
                    }
                  }
                  
                  // 每次收到数据都立即调用回调，实现流式显示
                  if (hasReceivedData) {
                    onMessage?.(fullResponse);
                  }
                }
                
                // 保存会话ID
                if (json.conversation_id && !conversationId) {
                  conversationId = json.conversation_id;
                  console.log('获取到会话ID:', conversationId);
                }
              } else if (json.event === 'message_end') {
                // 消息结束
                if (json.conversation_id && !conversationId) {
                  conversationId = json.conversation_id;
                  console.log('消息结束，会话ID:', conversationId);
                }
                // 确保最后一次调用回调
                if (fullResponse) {
                  onMessage?.(fullResponse);
                }
                // 触发完成回调
                onComplete?.();
              } else if (json.event === 'error') {
                const errorMsg = json.message || json.error || 'Unknown error';
                console.error('Dify返回错误:', errorMsg);
                throw new Error(errorMsg);
              }
            } else {
              // 没有event字段，直接检查是否有answer（兼容其他格式）
              if (json.answer || json.text || json.content) {
                const answerText = json.answer || json.text || json.content;
                // 检查是否是增量
                if (fullResponse && answerText.length > fullResponse.length) {
                  // 可能是增量，追加新部分
                  const newPart = answerText.substring(fullResponse.length);
                  if (newPart) {
                    fullResponse += newPart;
                  } else {
                    fullResponse = answerText;
                  }
                } else if (!fullResponse) {
                  fullResponse = answerText;
                } else {
                  fullResponse += answerText;
                }
                hasReceivedData = true;
                console.log('直接更新回答内容（无event），当前长度:', fullResponse.length);
                onMessage?.(fullResponse);
              }
              
              // 保存会话ID
              if (json.conversation_id && !conversationId) {
                conversationId = json.conversation_id;
              }
            }
          } catch (e) {
            console.warn('解析SSE数据失败:', data, e);
            // 如果是纯文本，尝试直接作为消息
            if (data && !data.startsWith('{')) {
              fullResponse += data;
              hasReceivedData = true;
              onMessage?.(fullResponse);
            }
          }
        } else if (line.startsWith('event: ')) {
          // 处理event行
          const eventType = line.slice(7).trim();
          console.log('收到事件类型:', eventType);
        }
      }
    }

    if (!hasReceivedData && !fullResponse) {
      console.warn('未收到任何数据，可能是响应格式不匹配');
    }

    // 最后尝试解析剩余的数据
    if (buffer.trim()) {
      console.log('处理剩余的缓冲区数据:', buffer);
      if (buffer.startsWith('data: ')) {
        const data = buffer.slice(6).trim();
        if (data !== '[DONE]' && data) {
          try {
            const json = JSON.parse(data);
            console.log('解析剩余数据的JSON:', json);
            if (json.answer || json.text || json.content) {
              const answerText: string = json.answer || json.text || json.content;
              fullResponse += answerText;
              hasReceivedData = true;
              onMessage?.(fullResponse);
            }
            if (json.conversation_id && !conversationId) {
              conversationId = json.conversation_id;
            }
          } catch (e) {
            console.warn('解析剩余数据失败:', e);
          }
        }
      }
    }

    console.log('最终返回数据:', {
      conversation_id: conversationId || conversation_id || undefined,
      answerLength: fullResponse.length,
      hasReceivedData,
    });

    return {
      conversation_id: conversationId || conversation_id || undefined,
      answer: fullResponse,
    };
  } catch (error) {
    const err = error instanceof Error ? error : new Error('Unknown error');
    onError?.(err);
    throw err;
  }
}

